package com.example.linuxchat;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.linuxchat.adapter.MessagesListAdapter;
import com.example.linuxchat.bean.ChatMessage;
import com.example.linuxchat.bean.User;
import com.example.linuxchat.utiltool.MyToast;
import com.example.linuxchat.utiltool.Time;
import com.loopj.android.image.SmartImageView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ChatActivity extends AppCompatActivity {
    RecyclerView message_list;
    SwipeRefreshLayout list_refresh;
    Button btn_send,btn_logout;
    SmartImageView imageView;
    TextView tx_message;
    MessagesListAdapter messagesAdapter;
    int nowNumber=-1;                 //记录已有最早消息的序号
    boolean isConnect=true;       //是否断开连接
    boolean isLoading=false;      //是否在加载
    //socket流
    OutputStream os ;
    InputStream is;
    Socket server;

    //用户信息
    public static String USER_ID;
    public static String USER_NAME;
    public static String USER_IMAGE;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String rec=(String)msg.obj;
            String[] result=rec.split("@");
            synchronized (this) {
                switch (msg.what) {
                    case 1:         //第一次加载
                    case 2:         //加载更多
                        for (int i = 0; i < result.length; i++) {
                            String[] msgs = result[i].split("#");
                            if (msgs.length >= 6) {
                                ChatMessage message = new ChatMessage(Integer.parseInt(msgs[0]), msgs[1], msgs[2], msgs[3], msgs[4], msgs[5]);
                                messagesAdapter.addFirst(message);
                                Log.d("backmessage",message.toString());
                            }
                        }
                        nowNumber = messagesAdapter.getFirstNumber();
                        Log.d("backmessage","nowNumber为: "+nowNumber);

                        if(nowNumber<=0){   //没有更多消息了
                            list_refresh.setEnabled(false);
                        }

                        if(isLoading){      //取消加载动画
                            list_refresh.setRefreshing(false);
                            isLoading=false;
                        }
                        break;
                    case 3:  //获取用户的消息
                        for (int i = 0; i < result.length; i++) {
                            String[] msgs = result[i].split("#");
                            if (msgs.length >= 6) {
                                ChatMessage message = new ChatMessage(Integer.parseInt(msgs[0]), msgs[1], msgs[2], msgs[3], msgs[4], msgs[5]);
                                messagesAdapter.addLast(message);
                            }
                        }
                        break;
                }
                if(msg.what==1){
                    message_list.scrollToPosition(messagesAdapter.getItemCount()-1);
                }
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        initWidget();
        initView();
    }

    private void initWidget(){
        message_list=(RecyclerView)findViewById(R.id.message_list);
        list_refresh=(SwipeRefreshLayout)findViewById(R.id.list_refresh);
        btn_send=(Button)findViewById(R.id.btn_send);
        btn_logout=(Button)findViewById(R.id.btn_logout);
        imageView=(SmartImageView)findViewById(R.id.imageView);
        tx_message=(TextView)findViewById(R.id.tx_message);
    }

    private void initView(){
        setUserInfo();      //设置信息
        setBtn_send();      //发送按钮

        setList_refresh();
        setMessage_list();
        setBtn_logout();
        setImageView();

        startServer();        //启动读线程
    }

    //加载更多信息
    private void setList_refresh(){
        list_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isLoading=true;
                new Thread(){
                    @Override
                    public void run() {
                        if(-1==nowNumber) {
                            list_refresh.setRefreshing(false);
                            isLoading=false;
                            return;
                        }
                        String sentMessage="3^"+nowNumber;
                        try {
                            os.write(sentMessage.getBytes());
                        } catch (IOException e) {
                            isConnect=false;
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
    }
    //设置列表
    private void setMessage_list(){
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        message_list.setLayoutManager(linearLayoutManager);
        messagesAdapter=new MessagesListAdapter();
        message_list.setAdapter(messagesAdapter);

    }
    //发送消息
    private void setBtn_send(){
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content=dealString(tx_message.getText().toString());
                if(TextUtils.isEmpty(content)) {
                    MyToast.makeText(ChatActivity.this, "请输入内容").show();
                    return;
                }
                if(content.length()>=400) {
                    MyToast.makeText(ChatActivity.this, "消息长度不能超过400").show();
                    return;
                }
                final ChatMessage message=new ChatMessage();
                message.setId(USER_ID);
                message.setName(USER_NAME);
                message.setTime(Time.getNowTime());
                message.setContent(content);
                message.setImageUrl(USER_IMAGE);

                tx_message.setText("");
                synchronized (this) {
                    messagesAdapter.addLast(message);                   //列表更新
                    message_list.scrollToPosition(messagesAdapter.getItemCount()-1);

                }

                new Thread(){
                    @Override
                    public void run() {
                        try {
                            os.write(message.toMessage().getBytes());       //发送消息
                        } catch (IOException e) {
                            isConnect=false;
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
    }
    //去除危险字符'#','^',' '
    public static String dealString(String str){
        return str.replaceAll(" ","").replaceAll("`","").replaceAll("#","");
    }
    //Tcp连接
    public void initSocket(){
        try {
            server=new Socket("liulingjie.cn",6667);
            os=server.getOutputStream();
            is=server.getInputStream();
            Log.d("backmessage","连接成功");
            String loginInfo="1`"+USER_ID+"#"+USER_NAME;
            os.write(loginInfo.getBytes());

        } catch (IOException e) {
            isConnect=false;
            e.printStackTrace();
        }
    }
    //读取信息
    public void readInput(){
        byte[] buffer=new byte[2048];
        int len=0;
        while (true) {
            if(!isConnect)break;            //连接断开退出
            try {
                len = is.read(buffer, 0, 2048);
                byte[] buffer1=new byte[len];
                for (int i=0;i<len;i++){
                    buffer1[i]=buffer[i];
                }
                String rec=new String(buffer1);
                Log.d("backmessage","返回数据  "+rec+"\n");

                if(!"notMore".equals(rec)){
                    Message msg=new Message();
                    msg.obj=rec;
                    if(-1==nowNumber){
                        msg.what=1;
                    }else{
                        int number=0;
                        try{number=Integer.parseInt(rec.substring(0,rec.indexOf('#'))); }catch (NumberFormatException e){e.getStackTrace();}//获取返回数据第一个消息的序号
                        Log.d("backmessage","返回数据第一个序号是: "+number+"\n");
                        if(number<nowNumber){
                            msg.what=2;
                        }else {
                            msg.what=3;
                        }
                    }
                    handler.sendMessage(msg);
                }else {
                    if(isLoading){      //取消加载动画
                        list_refresh.setRefreshing(false);
                        isLoading=false;
                    }
                }
            } catch (IOException e) {
                isConnect=false;
            }
        }
    }
    private void setBtn_logout(){
        btn_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出处理
                SharedPreferences sp=ChatActivity.this.getSharedPreferences("user_info", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor=sp.edit();
                editor.clear();
                editor.commit();

                //跳转
                Intent intent=new Intent(ChatActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void setImageView(){
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转
                Intent intent=new Intent(ChatActivity.this,UserInfoActivity.class);
                startActivity(intent);
            }
        });
    }
    //开启tcp线程
    private void startServer(){
        new Thread(){
            @Override
            public void run() {
                initSocket();       //Tcp连接
                readInput();        //开始读取内容
            }
        }.start();
    }
    //设置信息
    private void setUserInfo(){
        Intent intent=getIntent();
        User user=(User)intent.getSerializableExtra("user");
        USER_ID=user.getId().trim();
        USER_IMAGE=user.getUrl().trim();
        USER_NAME=user.getNickname().trim();
        imageView.setImageUrl(USER_IMAGE);
    }
    //销毁

    @Override
    protected void onDestroy() {
        super.onDestroy();
        new Thread(){
            @Override
            public void run() {
                try {
                    os.write("4".getBytes());
                } catch (IOException e) {
                    isConnect=false;
                    e.printStackTrace();
                }
                try {
                    os.close();
                    is.close();
                    server.close();
                } catch (IOException e) {
                    isConnect=false;
                    e.printStackTrace();
                }

            }
        }.start();
    }

    boolean isExist=false;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(isExist){
                finish();
            }else{
                isExist=true;
                MyToast.makeText(ChatActivity.this,"再按一次退出").show();
                new Thread(){
                    @Override
                    public void run() {
                        try {
                            sleep(2000);                //两秒后恢复原样
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        isExist=false;
                    }
                }.start();
            }
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
//    public static void main(String[] args){
//        String rec="20#333#jie#???#2020-06-19 10:04:40#no@19#333#jie#???#2020-02-02 00:00:00#url";
//        String[] result=rec.split("@");
//        for(int i=0;i<result.length;i++){
//            String[] msgs=result[i].split("#");
//            if(msgs.length>=6){
//                ChatMessage message=new ChatMessage(Integer.parseInt(msgs[0]),msgs[1],msgs[2],msgs[3],msgs[4],msgs[5]);
//                System.out.println(message);
//            }
//        }

//        String str="  `2 0#333#jie#?`??#2020-06-1`9 10:04:4 0#no@19#333#jie#??? #`2020-^02-02 00:00 :00#url#```";
//        System.out.println(dealString(str));
//    }

}
